package org.openstreetmap.josm.plugins.cadastre_es;

public abstract class Bresenham<T> {
	protected T rValue;
	
	/**
	 * Bresenham's line algorithm
	 * @param start point
	 * @param end point
	 */
	public Bresenham(Pixel start, Pixel end) {
		int x0 = start.x();
		int x1 = end.x();
		int y0 = start.y();
		int y1 = end.y();
        int dy = y1 - y0;
        int dx = x1 - x0;
        int stepx, stepy;
        Pixel p = new Pixel(); 

        if (dy < 0) { dy = -dy;  stepy = -1; } else { stepy = 1; }
        if (dx < 0) { dx = -dx;  stepx = -1; } else { stepx = 1; }
        dy <<= 1;                                                  // dy is now 2*dy
        dx <<= 1;                                                  // dx is now 2*dx
        
        if (dx > dy) {
            int fraction = dy - (dx >> 1);                         // same as 2*dy - dx
            while (x0 != x1) {
                if (fraction >= 0) {
                    y0 += stepy;
                    fraction -= dx;                                // same as fraction -= 2*dx
                }
                x0 += stepx;
                fraction += dy;                                    // same as fraction -= 2*dy
                p.x(x0);
                p.y(y0);
                run(p);
            }
        } else {
            int fraction = dx - (dy >> 1);
            while (y0 != y1) {
                if (fraction >= 0) {
                    x0 += stepx;
                    fraction -= dy;
                }
                y0 += stepy;
                fraction += dx;
                p.x(x0);
                p.y(y0);
                run(p);
            }
        }
        rValue = end();
	}
	
	public T getRvalue() {
		return rValue;
	}
	
	protected abstract void run(Pixel p);
	
	public abstract T end();
}
